package com.dongnam.quanly.web.danhmuc.nhanvien;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import org.primefaces.context.RequestContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dongnam.quanly.common.controller.NhanVienController;
import com.dongnam.quanly.common.exceptions.DatabaseException;
import com.dongnam.quanly.common.model.NhanVien;
import com.dongnam.quanly.common.model.enumtype.GioiTinh;
import com.dongnam.quanly.web.UserBean;
import com.dongnam.quanly.web.util.DateFormatUtil;
import com.dongnam.quanly.web.util.WebUtil;

@ManagedBean(name = "NhanVienBean")
@SessionScoped
public class NhanVienBean implements Serializable {

	private static final Logger logger = LoggerFactory.getLogger(NhanVienBean.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@ManagedProperty(value = "#{UserBean}")
	private UserBean userBean;
	private NhanVienModel nhanVienModel;

	// for add NhanVien
	private NhanVien nhanvien;
	private boolean isEdit = false;
	// for download file
	private StreamedContent file;

	// for load danh sach phong ban
	private NhanVienController nhanVienController;
	private List<NhanVien> listNhanVien;

	// for edit phongBan
	private NhanVien selectedNhanVien;

	public NhanVienBean() {
		super();
		nhanvien = new NhanVien();
		loadNhanVien();
		// TODO Auto-generated constructor stub
	}

	public NhanVienController getNhanVienController() {

		if (nhanVienController == null)
			nhanVienController = new NhanVienController();
		return nhanVienController;
	}

	public void downloadFileCSV() {
		File excelfile = new File("NHAN_VIEN.xls");
		List<NhanVien> list = getNhanVienController().findAll();
		int length = list.size();
		try {
			WritableWorkbook workbook = Workbook.createWorkbook(excelfile);
			WritableSheet sheet = workbook.createSheet("First Sheet", 0);

			// style for title
			WritableFont titlefont = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD);
			WritableCellFormat titleformat = new WritableCellFormat(titlefont);
			titleformat.setAlignment(Alignment.LEFT);
			titleformat.setWrap(false);

			// style for content
			WritableFont contentfont = new WritableFont(WritableFont.ARIAL, 13);
			WritableCellFormat contentformat = new WritableCellFormat(contentfont);
			contentformat.setAlignment(Alignment.LEFT);
			contentformat.setWrap(false);

			// thiet lap tieu de
			sheet.setColumnView(0, 30);
			sheet.setColumnView(1, 30);
			sheet.setColumnView(2, 30);
			sheet.setColumnView(3, 30);
			sheet.setColumnView(4, 30);
			sheet.setColumnView(5, 30);
			sheet.setColumnView(5, 30);
			sheet.setColumnView(6, 30);
			sheet.setColumnView(7, 30);
			sheet.setColumnView(8, 30);
			sheet.setColumnView(9, 30);
			sheet.setColumnView(10, 30);
			sheet.setColumnView(11, 30);
			sheet.setColumnView(12, 30);
			sheet.setColumnView(13, 30);
			sheet.setColumnView(14, 30);
			sheet.setColumnView(15, 30);
			sheet.setColumnView(16, 30);
			sheet.setColumnView(17, 30);

			sheet.addCell(new Label(0, 0, "Mã Nhân Viên", titleformat));
			sheet.addCell(new Label(1, 0, "Tên Nhân Viên", titleformat));
			sheet.addCell(new Label(2, 0, "Giới tính", titleformat));
			sheet.addCell(new Label(3, 0, "Ngày sinh", titleformat));
			sheet.addCell(new Label(4, 0, "Mã Số Thuế", titleformat));
			sheet.addCell(new Label(5, 0, "Phòng ban", titleformat));
			sheet.addCell(new Label(6, 0, "Chức vụ", titleformat));
			sheet.addCell(new Label(7, 0, "Số chứng minh", titleformat));
			sheet.addCell(new Label(8, 0, "Nơi cấp CMND", titleformat));
			sheet.addCell(new Label(9, 0, "Ngày cấp CMND", titleformat));
			sheet.addCell(new Label(10, 0, "Hệ số lương", titleformat));
			sheet.addCell(new Label(11, 0, "Giảm trừ gia cảnh", titleformat));
			sheet.addCell(new Label(12, 0, "Địa chỉ", titleformat));
			sheet.addCell(new Label(13, 0, "Điện thoại cơ quan", titleformat));
			sheet.addCell(new Label(14, 0, "Điện thoại nhà riêng", titleformat));
			sheet.addCell(new Label(15, 0, "Điện thoại di động", titleformat));
			sheet.addCell(new Label(16, 0, "Email", titleformat));
			sheet.addCell(new Label(17, 0, "Trạng thái", titleformat));

			for (int i = 0; i < length; i++) {

				sheet.addCell(new Label(0, i + 1, list.get(i).getMaNhanVien(), contentformat));
				sheet.addCell(new Label(1, i + 1, list.get(i).getHoTen(), contentformat));
				sheet.addCell(new Label(2, i + 1, list.get(i).getGioiTinh().name(), contentformat));
				sheet.addCell(new Label(3, i + 1, DateFormatUtil.Date2String("dd-MM-yyyy", list.get(i).getNgaySinh()),
						contentformat));

				sheet.addCell(new Label(4, i + 1, list.get(i).getMaSoThue(), contentformat));
				sheet.addCell(new Label(5, i + 1, list.get(i).getPhongBan(), contentformat));
				sheet.addCell(new Label(6, i + 1, list.get(i).getChucVu(), contentformat));
				sheet.addCell(new Label(7, i + 1, list.get(i).getSoCMND(), contentformat));
				sheet.addCell(new Label(8, i + 1, list.get(i).getNoiCapCMND(), contentformat));

				sheet.addCell(new Label(9, i + 1, list.get(i).getNgayCapCMND() != null ? DateFormatUtil.Date2String(
						"dd-MM-yyyy", list.get(i).getNgayCapCMND()) : "", contentformat));
				sheet.addCell(new Label(10, i + 1, list.get(i).getHeSoLuong(), contentformat));
				sheet.addCell(new Label(11, i + 1, String.valueOf(list.get(i).getGiamTruGiaCanh()), contentformat));
				sheet.addCell(new Label(12, i + 1, list.get(i).getDiaChi(), contentformat));
				sheet.addCell(new Label(13, i + 1, list.get(i).getdTCoQuan(), contentformat));
				sheet.addCell(new Label(14, i + 1, list.get(i).getdTNhaRieng(), contentformat));
				sheet.addCell(new Label(15, i + 1, list.get(i).getdTDiDong(), contentformat));
				sheet.addCell(new Label(16, i + 1, list.get(i).getEmail(), contentformat));
				sheet.addCell(new Label(17, i + 1, list.get(i).getTrangthai(), contentformat));

			}

			workbook.write();
			workbook.close();

			file = new DefaultStreamedContent(new FileInputStream(excelfile), "application/csv", "NHAN_VIEN.xls",
					"UTF-8");

		} catch (IOException | WriteException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	public void handleFileUpload(FileUploadEvent event) {

		logger.debug("process upload file ");
		Workbook w;
		boolean rollback = false;
		List<NhanVien> list = new ArrayList<NhanVien>();
		try {
			w = Workbook.getWorkbook(event.getFile().getInputstream());
			// Get the first sheet
			Sheet sheet = w.getSheet(0);
			// Loop over first 10 column and lines

			for (int row = 1; row < sheet.getRows(); row++) {

				logger.debug("row " + row);
				Cell cell_ma = sheet.getCell(0, row);
				Cell cell_ten = sheet.getCell(1, row);
				Cell cell_gioitinh = sheet.getCell(2, row);
				Cell cell_ngaysinh = sheet.getCell(3, row);
				Cell cell_masothue = sheet.getCell(4, row);
				Cell cell_phongban = sheet.getCell(5, row);
				Cell cell_chucvu = sheet.getCell(6, row);
				Cell cell_soCMND = sheet.getCell(7, row);
				Cell cell_noicapCMND = sheet.getCell(8, row);
				Cell cell_NgayCapCMND = sheet.getCell(9, row);
				Cell cell_HeSoLuong = sheet.getCell(10, row);
				Cell cell_GiamTruGiaCanh = sheet.getCell(11, row);
				Cell cell_DiaChi = sheet.getCell(12, row);
				Cell cell_dTCoQuan = sheet.getCell(13, row);
				Cell cell_dTNhaRieng = sheet.getCell(14, row);
				Cell cell_dTDiDong = sheet.getCell(15, row);
				Cell cell_Email = sheet.getCell(16, row);
				Cell cell_Trangthai = sheet.getCell(17, row);

				NhanVien nv = new NhanVien();
				nv.setMaNhanVien(cell_ma.getContents());
				nv.setHoTen(cell_ten.getContents());
				nv.setGioiTinh(GioiTinh.valueOf(cell_gioitinh.getContents()));
				nv.setNgaySinh(DateFormatUtil.String2Date("dd-MM-yyyy", cell_ngaysinh.getContents()));
				nv.setMaSoThue(cell_masothue.getContents());
				nv.setPhongBan(cell_phongban.getContents());
				nv.setChucVu(cell_chucvu.getContents());
				nv.setSoCMND(cell_soCMND.getContents());
				nv.setNoiCapCMND(cell_noicapCMND.getContents());
				nv.setNgayCapCMND(DateFormatUtil.String2Date("dd-MM-yyyy", cell_NgayCapCMND.getContents()));
				nv.setHeSoLuong(cell_HeSoLuong.getContents());
				nv.setGiamTruGiaCanh(Double.parseDouble(cell_GiamTruGiaCanh.getContents()));
				nv.setDiaChi(cell_DiaChi.getContents());
				nv.setdTCoQuan(cell_dTCoQuan.getContents());
				nv.setdTNhaRieng(cell_dTNhaRieng.getContents());
				nv.setdTDiDong(cell_dTDiDong.getContents());
				nv.setEmail(cell_Email.getContents());
				nv.setTrangthai(cell_Trangthai.getContents());
				list.add(nv);
			}
		} catch (BiffException | IOException e) {
			e.printStackTrace();
			rollback = true;
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful : Database error : "
					+ e.getMessage(), "");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}

		if (!rollback) {
			getNhanVienController().batchSaveOrUpdate(list);
		}

		loadNhanVien();
	}

	public void resetFormAdd() {
		nhanvien = new NhanVien();
	}

	public void notifyAdd() {
		isEdit = false;
		resetFormAdd();
	}

	public void notifyEdit(NhanVien nhanvien) {
		isEdit = true;
		this.selectedNhanVien = nhanvien;
		this.nhanvien.fillNhanVien(nhanvien);
	}

	public void removeNhanVien() {

		if (this.selectedNhanVien != null) {
			getNhanVienController().makeTransient(this.selectedNhanVien);
			loadNhanVien();
			listNhanVien = getNhanVienController().findAll();
		}

	}

	public void save() {

		RequestContext context = RequestContext.getCurrentInstance();
		try {
			if (isEdit) {
				logger.debug("Edit new NhanVien");

				if (this.selectedNhanVien != null) {

					getNhanVienController().makeTransient(this.selectedNhanVien);

					this.selectedNhanVien.fillNhanVien(this.nhanvien);
					this.selectedNhanVien.setUpdateBy(userBean.getUser().getUserId());

					getNhanVienController().makePersistent(this.selectedNhanVien);
					// change state of parent
					context.addCallbackParam("opSuccess", true);
				}

			} else {

				logger.debug("Add new NhanVien :" + this.nhanvien.getHoTen());
				NhanVien nv = new NhanVien();
				nv.setCreateBy(userBean.getUser().getUserId());
				nv.setUpdateBy(userBean.getUser().getUserId());

				nv.fillNhanVien(this.nhanvien);

				getNhanVienController().makePersistent(nv);

				listNhanVien = getNhanVienController().findAll();
				context.addCallbackParam("opSuccess", true);

			}
		} catch (DatabaseException e) {
			e.printStackTrace();
			logger.debug("Database error" + e.getMessage());
			context.addCallbackParam("opSuccess", false);

			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful : Database error : "
					+ e.getMessage(), "");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}

		loadNhanVien();

	}

	public void loadNhanVien() {
		if (nhanVienModel == null)
			nhanVienModel = new NhanVienModel();

		nhanVienModel.init();
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}

	public UserBean getUserBean() {
		return userBean;
	}

	public void setUserBean(UserBean userBean) {
		this.userBean = userBean;
	}

	public void reloadPage() {
		loadNhanVien();
		WebUtil.redirect("/pages/danhmuc/nhanVien.xhtml");
	}

	public NhanVienModel getNhanVienModel() {
		return nhanVienModel;
	}

	public void setNhanVienModel(NhanVienModel nhanVienModel) {
		this.nhanVienModel = nhanVienModel;
	}

	public NhanVien getNhanvien() {
		return nhanvien;
	}

	public void setNhanvien(NhanVien nhanvien) {
		this.nhanvien = nhanvien;
	}

	public NhanVien getSelectedNhanVien() {
		return selectedNhanVien;
	}

	public void setSelectedNhanVien(NhanVien selectedNhanVien) {
		this.selectedNhanVien = selectedNhanVien;
	}

	public List<NhanVien> getListNhanVien() {
		if (listNhanVien == null) {
			listNhanVien = getNhanVienController().findAll();
		}
		return listNhanVien;
	}

	public void setListNhanVien(List<NhanVien> listNhanVien) {
		this.listNhanVien = listNhanVien;
	}

	public GioiTinh[] getListGioiTinh() {
		return GioiTinh.values();
	}

}
